package com.gg.jdbc.generate;

import com.gg.jdbc.DB2Connection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SysTables {
	
	protected Connection connection;
	
	protected ResultSet rs;
	
	protected ResultSetMetaData data;
	
	protected String creator;
	
	protected String[] names;
	
	public SysTables(Connection connection, String creator) {
		this.connection = connection;
		this.creator    = creator;
	}

	public boolean execSQL() {
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT NAME FROM SYSIBM.SYSTABLES ");
		sb.append("  WHERE CREATOR = ? ");
		sb.append("    AND TYPE    = 'T' ");
		sb.append("  ORDER BY NAME ");
		
		try {
			PreparedStatement s = connection.prepareStatement(sb.toString());
			s.setString(1, creator);
			
			rs      = s.executeQuery();
			data    = rs.getMetaData();
			
			getResultData();
			
			rs.close();
			s.close();
			
			return true;
		
		} catch (SQLException e) {
			DB2Connection.sqlException(e);
		}
		return false;
	}
	
	protected void getResultData() throws SQLException {
		List<String> list = new ArrayList<String>();
		
		while (rs.next()) {
			String table = rs.getString("NAME");
			if (execSelectSQL(table)) list.add(table);
		}
		
		names =  (String[]) list.toArray(new String[list.size()]);
	}
	
	public String[] getTableNames() {
		return names;
	}
	
	protected boolean execSelectSQL(String table) {
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT * FROM ");
		sb.append(creator);
		sb.append(".");
		sb.append(table);
		sb.append(" FETCH FIRST ROW ONLY");
//		System.out.println(sb.toString());
		
		try {
			PreparedStatement s = connection.prepareStatement(sb.toString());
			
			ResultSet rs      = s.executeQuery();
			
			s.close();
			rs.close();
			
			return true;
		
		} catch (SQLException e) {
			System.out.println("**** Table " + table + "; SQLCODE = " + e.getErrorCode());
		}
		return false;
	}
	
}
